﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GuoZhiQi.MiddleCache.Parameter
{
    public class CouchBaseString : CouchBaseParameter<string>
    {
        #region Value.

        /// <summary>
        /// Get the value of current parameter.
        /// </summary>
        public override string Value
        {
            get;
            set;
        }

        #endregion Value.

        #region Constructor.

        public CouchBaseString(CouchBaseObject Parent, string paramKey)
            : base(Parent, paramKey)
        {
            this.Value = null;
        }

        #endregion Constructor.

        #region Atomic functions.

        /// <summary>
        /// Appends string to the parameter and refreshes with new value. Atomic function.
        /// </summary>
        /// <param name="client">Client.</param>
        /// <param name="addedString">String to be appended.</param>
        public void Append(string addedString)
        {
            if (this.Key == null)
                throw new NullReferenceException("Key is not set yet.");

            if (!this.Client.Append(this.Key, new ArraySegment<byte>(Encoding.UTF8.GetBytes(this.Value))))
                throw new NullReferenceException("Key not found in database.");

            this.Value = (string)this.Client.Get(this.Key);
        }

        /// <summary>
        /// Prepends string to the parameter and refreshes with new value. Atomic function.
        /// </summary>
        /// <param name="client">Client.</param>
        /// <param name="addedString">String to be prepended.</param>
        public void Prepend(string addedString)
        {
            if (this.Key == null)
                throw new NullReferenceException("Key is not set yet.");

            if (!this.Client.Prepend(this.Key, new ArraySegment<byte>(Encoding.UTF8.GetBytes(this.Value))))
                throw new NullReferenceException("Key not found in database.");

            this.Value = (string)this.Client.Get(this.Key);
        }

        #endregion Atomic functions.
    }
}
